<?php
/**
 * @Created by PhpStorm.
 * @Name 资金管理控制器
 * @User: Wong
 * @Date: 2016/11/18
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace admin\action;

use herosphp\http\HttpRequest;
use herosphp\core\Log;
use api\utils\PayApiClient;
use herosphp\utils\AjaxResult;

/**--tmpl-use--**/

class FundAction extends CommonAction {

	public function C_start(){
		parent::C_start();
	}

    /**
     * 流水类型名称
     * @param null $k
     * @return array|mixed
     */
    public function logTypes($k=null){
        $arr = array(
            'inpay' => '入金',
            'outpay' => '出金',
            'cash' => '提现',
            'pay' => '支付',
            'confirm' => '确认收货'
        );
        return $k?$arr[$k]:$arr;
    }

    public function index(HttpRequest $request) {
        $userInfo = $this->__getUserInfo('*');
        $data['userid'] = $userInfo['userid'];
        $url = "api/payment/getBalance";
        $result = PayApiClient::send($url, $data);
        if($result->isSucess()){
            $res = $result->getData();
            $balance = $res['balance'];
        }else{
            Log::info($result->getMessage());
            $balance = 0;

        }
        $balance = setFloat($balance,2);
        //5条资金流水
        $conditions = array();
        $conditions['userid'] = $userInfo['userid'];
        $data['conditions'] = $conditions;
        $data['order'] = array('addtime' => '-1');
        $data['page'] = '1';
        $data['pagesize'] = '5';
        $url = "api/userLog/getUserLogs";
        $result = PayApiClient::send($url, $data);
        if ( $result->isSucess() ) {
            $items = $result->getItems();
        } else {
            Log::info($result->getMessage());
            $items = array();
        }
        foreach($items as $k=>$v){
            $items[$k]['type_name'] = $this->logTypes($v['type']);
        }
        $this->assign('items',$items);
        $this->assign('userInfo',$userInfo);
        $this->assign('balance',$balance);
        $this->assign("title", "资金总览");
        $this->assign('bread', array('资金管理',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/index');
    }

    /**
     * 资金流水
     * @param HttpRequest $request
     */
    public function log(HttpRequest $request) {
        $type = $request->getParameter('type');
        $s_time = $request->getParameter('s_time');
        $e_time = $request->getParameter('e_time');
        $username = $request->getParameter('username');
        $serial_no = $request->getParameter('serial_no');
        $order_no = $request->getParameter('order_no');
        $pagesize = $request->getParameter('pagesize') ? $request->getParameter('pagesize') : $this->getPagesize();
        $page = $request->getParameter('page');
        $page = $page>0?$page:1;
        $this->setPage($page);
        $this->setPagesize($pagesize);

        //todo 获取用户流水
        $conditions = array();
        if($type) $conditions['type'] = $type;
        if($s_time) $conditions['addtime']['>'] = $s_time;
        if($e_time) $conditions['addtime']['<='] = $e_time.' 23:59:59';
        if($username) $conditions['username']= $username;
        if($serial_no) $conditions['serial_no']= $serial_no;
        if($order_no) $conditions['order_no']= $order_no;

        //单选导出 add By Laoliu 2016-12-19 16:21:50
        if( $request -> getParameter('export') == 1 ){
            $page = 1;
            $pagesize = 2147483648;
            $ids = $request -> getParameter('ids');
            if( is_array($ids) ){
                $conditions['id']['$in'] = $ids;
            }
        }

        if(!empty($conditions)) $data['conditions'] = $conditions;
        $data['order'] = array('addtime' => '-1');
        $data['page'] = (string)$page;
        $data['pagesize'] = (string)$pagesize;
        $url = "api/userLog/getUserLogs";
        $result = PayApiClient::send($url, $data);
        if ( $result->isSucess() ) {
            $items = $result->getItems();
            $total = $result->getCount();
        } else {
            Log::info($result->getMessage());
            $items = array();
        }

        foreach($items as $k=>$v){
            $items[$k]['type_name'] = $this->logTypes($v['type']);
        }
        //导出excel add By Laoliu 2016-12-19 16:21:50
        if( $request -> getParameter('export') == 1 ){
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["serial_no"];
                $tmp[] = $v["username"];
                $tmp[] = $v["amount"];
                $tmp[] = $v["usable"];
                $tmp[] = $v['atype']=='+'?'收入':($v['atype']=='-'?'支出':'---');
                $tmp[] = $v["type_name"];
                $tmp[] = ($v['type']=='pay' || $v['type']=='confirm')?'订单号：'.$v['order_no']:"-";
                $tmp[] = $v["addtime"];
                $excel[] = $tmp;
            }
            $header = array('流水号','大塑账户','发生额(￥)','可用资金(￥)','资金类型','业务类型','具体业务','交易时间');
            phpexcel("资金流水",$header,$excel);
            exit();
        }
        $this->generatePageMenu($total);

        $this->assign('items',$items);
        $this->assign('pagesize',$pagesize);
        $this->assign('type',$type);
        $this->assign('s_time',$s_time);
        $this->assign('e_time',$e_time);
        $this->assign('username',$username);
        $this->assign('serial_no',$serial_no);
        $this->assign('order_no',$order_no);

        $this->assign("title", "资金流水");
        $this->assign('bread', array('资金管理',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/log');
    }

    function deletes(HttpRequest $request){
        AjaxResult::ajaxSuccessResult();
    }

    function delete(HttpRequest $request){
        AjaxResult::ajaxSuccessResult();
    }

    /**
     * 入金
     * @param HttpRequest $request
     */
    public function inPay(HttpRequest $request){
        $data['userid'] = $this->__getUserInfo('id');
        $data['amount'] = $request->getParameter('amount','trim');
        $token = $request->getParameter('token','trim');

        if($_SESSION['payToken'] != $token){
            AjaxResult::ajaxResult('001','参数错误');
        }
        $url = "api/payment/inPay";

        $result = PayApiClient::send($url, $data);
        if($result->isSucess()){
            AjaxResult::ajaxSuccessResult();
        }else{
            Log::info($result->getMessage());
        }
    }

    /**
     * 出金
     * @param HttpRequest $request
     */
    public function outPay(HttpRequest $request){
        $data['userid'] = $this->__getUserInfo('id');
        $data['amount'] = $request->getParameter('amount','trim');
        $token = $request->getParameter('token','trim');

        if($_SESSION['payToken'] != $token){
            AjaxResult::ajaxResult('001','参数错误');
        }
        $url = "api/payment/outPay";

        $result = PayApiClient::send($url, $data);

        if($result->isSucess()){
            AjaxResult::ajaxSuccessResult();

        }else{
            Log::info($result->getMessage());
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 提现
     * @param HttpRequest $request
     */
    public function withdraw(HttpRequest $request){
        $data['userid'] = $this->__getUserInfo('id');
        $data['amount'] = $request->getParameter('amount','trim');
        $token = $request->getParameter('token','trim');

        if($_SESSION['payToken'] != $token){
            AjaxResult::ajaxResult('001','参数错误');
        }
        $url = "api/payment/withdraw";

        $result = PayApiClient::send($url, $data);
        if($result->isSucess()){
            AjaxResult::ajaxSuccessResult();

        }else{
            Log::info($result->getMessage());
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 查询用户余额
     */
    public function getBalance(){
        $data['userid'] = $this->__getUserInfo('id');
        $url = "api/payment/getBalance";
        $result = PayApiClient::send($url, $data);
        if($result->isSucess()){
            $res = $result->getData();
            $balance = $res['balance'];
        }else{
            Log::info($result->getMessage());
            $balance = 0;
        }
        $balance = setFloat($balance,2);
        AjaxResult::ajaxResult('000','用户余额',$balance);
    }

    /**
     * 检测用户是否签约 是否设置交易密码
     */
    public function isSign(){
        $userInfo = $this->__getUserInfo('tradepass,sign_status');
        if($userInfo['tradepass'] == ''){
            AjaxResult::ajaxResult('001','您还未设置交易密码,请先设置交易密码');
        }
        if ($userInfo['sign_status'] == 2){//解约
            AjaxResult::ajaxResult('001','已经解约');
        }elseif($userInfo['sign_status'] == '0'){//签约
            AjaxResult::ajaxResult('001','没有签约');
        }else{
            AjaxResult::ajaxSuccessResult();
        }
    }

    /**
     * 校验交易密码
     * @param HttpRequest $request
     */
    public function checkPayPassword(HttpRequest $request){
        $pwd = $request->getParameter('pwd','trim');
        $__token = md5(getRandStr(6));
        $_SESSION['payToken'] = $__token;
        $payPass = $this->__getUserInfo('tradepass');
        if(passwd($pwd) == $payPass){
            AjaxResult::ajaxResult('000','交易密码正确',array('token'=>$__token));

        }else{
            AjaxResult::ajaxResult('001','交易密码错误');
        }
    }

    /**
     * 返回签约的银行信息
     */
    public function bankInfo(){
        $signInfo = $this->__getUserInfo('payway,virtual_account,sign_bank_id');
        $data = array(
            'bankType'=>$signInfo['payway'],
            'virtualAccount'=>$signInfo['virtual_account'],
            'bankId'=>$signInfo['sign_bank_id'],
        );
        AjaxResult::ajaxResult('000','ok',$data);
    }

    /**
     * 修改交易密码
     * @param HttpRequest $request
     */
    public function do_tradePass(HttpRequest $request){
        $password = $request -> getParameter('password');
        $code = $request -> getParameter('vcode');
        $this -> timeOut();
        if( $code != $_SESSION['mpe_admin']['vcode'] ){
            unset($_SESSION['mpe_admin']['vcode']);
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"验证码错误!",null);
        }
        unset($_SESSION['mpe_admin']['vcode']);
        $user_info = $this->__getUserInfo('*');
        $user_id = $user_info['id'];
        $url = "api/user/tradePass";
        $result = PayApiClient::send( $url,array('userid'=>$user_id,'password'=>passwd($password)) );
        if( $result -> isSucess() ){
            $mobile = $user_info['username'];
            $username = $user_info['name'];
            $this -> sendBySaaSApi("MODIFY_TRADE_SUCCESS",array('【username】'=>$username),$mobile);
            Log::info($user_id." 更新了交易密码");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"保存成功，请牢记你的交易密码!",null);
        }else{
            Log::error($user_id." 更新交易密码失败,接口返回:".$result -> getMessage());
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"保存失败，请稍后再试！",null);
        }
    }

    /**
     * 调用SaaS接口发送短信
     * @param $rule
     * @param $data
     * @param $mobile
     * @return bool
     */
    protected function sendBySaaSApi( $rule, $data, $mobile ){
        $url = 'api/sms/getSMS';
        $result = PayApiClient::send($url,array('rule'=>$rule,'data'=>$data,'mobile'=>$mobile));
        if( $result -> isSucess() ){
            return true;
        }else{
            Log::error('调用SaaS短信接口失败，接口返回：'.$result->getMessage());
            return false;
        }
    }

    /**
     * 发送短信方法
     * @param HttpRequest $request
     */
    public function getSMS(HttpRequest $request){
        unset($_SESSION['mpe_admin']['vcode']);
        $mobile = $request -> getParameter('mobile','trim');
        $flag = $request -> getParameter('msgType','trim');
        if( $mobile ) {
            if (!preg_match('/^\d{11}$/', $mobile )) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "手机格式错误", null);
            }
        }
        $code = rand(1000,9999);
        session_start();
        $_SESSION['mpe_admin']['vcode'] = $code;
        if( !$flag || !in_array($flag,array(3)) ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
        switch( $flag ){
            case 3:
                $this -> checkTimeOut($mobile);
                $_SESSION['mpe_admin']['time'] = time();
                $_SESSION['sendMobile_admin'][] = $mobile;
                $rule = "MODIFY_TRADE_CODE";
                $mobile = $this->__getUserInfo('username');

                if($this -> sendBySaaSApi($rule,array('【code】'=>(string)$code),$mobile)) {
                    AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
                }else{
                    AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
                }
                break;//修改交易密码
            default:
                unset($_SESSION['mpe_admin']['time']);
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
    }

    /**
     * 重复发送手机短信时间
     * @param $mobile
     */
    protected function checkTimeOut($mobile){
        if( !in_array($mobile,$_SESSION['sendMobile_admin']) ){
            return;
        }
        $seconds = time() - $_SESSION['mpe_admin']['time'];
        if( $seconds < 120){
            $wait = 120-$seconds;
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"请等待{$wait}秒后再尝试发送",null);
        }
    }

    /**
     * 短信超时方法，统一为5分钟
     */
    public function timeOut(){
        if(time() - $_SESSION['mpe_admin']['time'] > 300){
            unset($_SESSION['mpe_admin']['vcode']);
        }

    }

}
